﻿using System.Data;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Yamfinder.Data.Tests
{
    [TestClass]
    public class DataDicIntegrationTests
    {
        private IDataSource _dataSource;
        private IDataDictonaryRepository _dataDicRepository;

        [TestInitialize]
        public void Init()
        {
            _dataSource = new DataSource();
            _dataDicRepository = new DataDictonaryRepository(_dataSource);
        }

        [TestMethod]
        public void IntergrationTest()
        {
            //Test Insert
            _dataDicRepository.Insert(new DataDictonaryEntry()
                                {IsDisplayed = false, IsRequired = false, Name = "TestDataDicValue1000", Type = "Number"});
            _dataDicRepository.Insert(new DataDictonaryEntry()
                                {IsDisplayed = false, IsRequired = false, Name = "TestDataDicValue2000", Type = "Number"});

            //Test Query
            Assert.IsTrue(_dataDicRepository.Query().Where(x => x.Name.StartsWith("TestDataDicValue")).Count() == 2);

            //Test Get w. Name
            var value1000 = _dataDicRepository.Get("TestDataDicValue1000");

            Assert.IsNotNull(value1000);
            Assert.AreEqual(value1000.Type,"Number");

            //Test Save
            value1000.Type = "Text";
            _dataDicRepository.Save(value1000);

            //Test Get w. Id
            value1000 = _dataDicRepository.Get(value1000.Id);

            Assert.IsNotNull(value1000);
            Assert.AreEqual(value1000.Type, "Text");

            var value2000 = _dataDicRepository.Get("TestDataDicValue2000");

            Assert.IsNotNull(value2000);

            //Test Remove w. Id and Text
            _dataDicRepository.Remove(value2000.Id);
            _dataDicRepository.Remove(value1000.Name);

            Assert.IsTrue(_dataDicRepository.Query().Where(x => x.Name.StartsWith("TestDataDicValue")).Count() == 0);
        }

        [TestMethod]
        [ExpectedException(typeof(DataException))]
        public void DuplicateFieldNamesTest()
        {
            //Should not let me have duplciate user names
            _dataDicRepository.Insert(new DataDictonaryEntry() { IsDisplayed = false, IsRequired = false, Name = "TestDataDicValue1000", Type = "Number" });

            //This should throw an exception
            _dataDicRepository.Insert(new DataDictonaryEntry() { IsDisplayed = false, IsRequired = false, Name = "TestDataDicValue1000", Type = "Number" });
        }

        [TestCleanup]
        public void Cleanup()
        {
            //Just in case these are left around
            _dataDicRepository.Remove("TestDataDicValue1000");
            _dataDicRepository.Remove("TestDataDicValue2000");
        }
    }
}
